﻿/*
 * @Autor: PK
 * @Date: 2021/12/11 18:07:SS
 */

using System;
using System.Collections.Generic;
using ShkSimulation.core.dao.output.result;
using ShkSimulation.core.exceptions;
using ShkSimulation.core.template.model;

namespace ShkSimulation.core.dao.statistic {
	
	public delegate CollectionReportData ExtractReportersAction(DataReporterCollection data);
	
	public abstract class ResultListener: Unique {
		
		public abstract string Uniquekey { get; }
		
		protected Dictionary<DataReporter, DataReporterCollection> reporterToCollection =
			new Dictionary<DataReporter, DataReporterCollection>();

		protected SortedSet<DataReporterCollection> collections = 
			new SortedSet<DataReporterCollection>(Comparer<DataReporterCollection>
				.Create((a,b) => String.Compare(a.Uniquekey, b.Uniquekey, StringComparison.Ordinal)));

		protected abstract void AppendData(CollectionReportData data);
		
		public ExtractReportersAction Action { get; set; }

		public abstract Result Export();
		
		public void BindTargetReporter(DataReporterCollection reporters) {
			if (collections.Contains(reporters)) {
				throw new ErrorParamException("Reporter集合重复");
			}
			collections.Add(reporters);
			reporters.OnReport += this.OnReporterReport;
		}
		
		public void RemoveTargetReporter(DataReporterCollection reporters) {
			if (!collections.Contains(reporters)) {
				throw new ErrorParamException($"Listener{Uniquekey}未监听{reporters.Uniquekey}");
			}
			collections.Remove(reporters);
			reporters.OnReport -= this.OnReporterReport;
		}
		
		public void OnReporterReport(DataReporterCollection data) {
			if (Action == null) {
				return;
			}
			AppendData(Action.Invoke(data));
		}

	}
}